<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告消息 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        effect="dark"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <div class="classify">
        <span>选择商品分类</span>
        <!-- options 用来指定数据源 -->
        <!-- props用来指定配置对象 -->
        <!-- handleChange只要级联选择器的选项发生了变化，就会触发这个函数 -->
        <!-- v-model 用于将选中的数据value值双向同步到一个数组中 -->
        <el-cascader
          v-model="chooseClassify.selectedCateKeys"
          :options="chooseClassify.cateList"
          :props="chooseClassify.cateProps"
          @change="handleChange"
          clearable
          change-on-select
          expandTrigger="hover"
        ></el-cascader>
      </div>
      <!-- tab页签区域 -->
      <el-tabs v-model="chooseClassify.activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showAddManyDataDialog"
            >添加参数</el-button
          >

          <!-- 添加动态参数表格 -->
          <el-table
            :data="chooseClassify.manyTableData"
            style="width: 100%;"
            border
            stripe
          >
            <el-table-column type="expand">
              <template #default="{row}">
                <!-- 文本标签 -->
                <el-tag
                  v-for="(item, index) in row.attr_vals"
                  :key="index"
                  class="tags"
                  closable
                  @close="deleteTag(index, row)"
                  >{{ item }}</el-tag
                >
                <!-- 文本标签输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{row}">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showManyEditDialog(row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showAddOnlyDataDialog"
            >添加属性</el-button
          >

          <!-- 添加静态属性表格 -->
          <el-table
            :data="chooseClassify.onlyTableData"
            style="width: 100%;"
            border
            stripe
          >
            <el-table-column type="expand">
              <template #default="{row}">
                <el-tag
                  v-for="(item, index) in row.attr_vals"
                  :key="index"
                  class="tags"
                  closable
                  @close="deleteTag(index, row)"
                  >{{ item }}</el-tag
                >
                <!-- 文本标签输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{row}">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showOnlyEditDialog(row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数对话框 -->
    <el-dialog
      title="添加动态参数"
      :visible.sync="chooseClassify.addManyDataVisible"
      width="50%"
      @close="addManyDataFormClosed"
    >
      <el-form
        :model="chooseClassify.addManyDataForm"
        :rules="chooseClassify.addManyDataRule"
        ref="addManyDataRef"
        label-width="100px"
      >
        <el-form-item label="动态参数" prop="attr_name">
          <el-input
            v-model="chooseClassify.addManyDataForm.attr_name"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="chooseClassify.addManyDataVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="addManyParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加静态属性对话框 -->
    <el-dialog
      title="添加静态属性"
      :visible.sync="chooseClassify.addOnlyDataVisible"
      width="50%"
      @close="addOnlyDataFormClosed"
    >
      <el-form
        :model="chooseClassify.addOnlyDataForm"
        :rules="chooseClassify.addOnlyDataRule"
        ref="addOnlyDataRef"
        label-width="100px"
      >
        <el-form-item label="静态属性" prop="attr_name">
          <el-input
            v-model="chooseClassify.addOnlyDataForm.attr_name"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="chooseClassify.addOnlyDataVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="addOnlyParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改动态参数的对话框 -->
    <el-dialog
      title="修改动态参数"
      :visible.sync="chooseClassify.editManyDataVisible"
      width="50%"
      @close="editManyDataFormClosed"
    >
      <el-form
        :model="chooseClassify.editManyDataForm"
        :rules="chooseClassify.editManyDataRule"
        ref="editManyDataRef"
        label-width="100px"
      >
        <el-form-item label="动态参数" prop="attr_name">
          <el-input
            v-model="chooseClassify.editManyDataForm.attr_name"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="chooseClassify.editManyDataVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="editManyParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改静态属性的对话框 -->
    <el-dialog
      title="修改静态属性"
      :visible.sync="chooseClassify.editOnlyDataVisible"
      width="50%"
      @close="editOnlyDataFormClosed"
    >
      <el-form
        :model="chooseClassify.editOnlyDataForm"
        :rules="chooseClassify.editOnlyDataRule"
        ref="editOnlyDataRef"
        label-width="100px"
      >
        <el-form-item label="静态属性" prop="attr_name">
          <el-input
            v-model="chooseClassify.editOnlyDataForm.attr_name"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="chooseClassify.editOnlyDataVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="editOnlyParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 选择商品分类区域
      chooseClassify: {
        cateList: [],
        cateProps: {
          // 记录当前选中的值
          value: 'cat_id',
          // 记录当前看到的值
          label: 'cat_name',
          // 用来指定父子嵌套属性
          children: 'children',
        },
        selectedCateKeys: [],
        activeName: 'many',
        // 存储静态属性
        onlyTableData: [],
        // 存储动态参数
        manyTableData: [],
        // 控制添加动态参数对话框的显示
        addManyDataVisible: false,
        // 添加动态参数的数组
        addManyDataForm: {
          attr_name: '',
        },

        // 添加动态参数的校验规则
        addManyDataRule: {
          attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' },
          ],
        },

        // 控制添加静态属性对话框的显示
        addOnlyDataVisible: false,
        // 添加静态属性的数组
        addOnlyDataForm: {
          attr_name: '',
        },

        // 添加静态属性的校验规则
        addOnlyDataRule: {
          attr_name: [
            { required: true, message: '请输入属性名称', trigger: 'blur' },
          ],
        },
        // 控制编辑动态参数的对话框
        editManyDataVisible: false,

        // 编辑动态参数数组
        editManyDataForm: {},
        // 编辑动态参数的校验规则
        editManyDataRule: {
          attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' },
          ],
        },
        // 控制编辑静态属性的对话框
        editOnlyDataVisible: false,

        // 编辑静态属性数组
        editOnlyDataForm: {},
        // 编辑静态属性的校验规则
        editOnlyDataRule: {
          attr_name: [
            { required: true, message: '请输入属性名称', trigger: 'blur' },
          ],
        },
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //  获取所有的商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories');
      if (res.meta.status !== 200) {
        return this.$Elementui.Message.error('获取商品列表数据失败！');
      }
      this.chooseClassify.cateList = res.data;
      //   console.log(this.chooseClassify.cateList);
    },
    // 选中级联选择项就会触发的事件
    async handleChange() {
      this.getParamsData();
    },
    // tab标签页处理函数
    handleTabClick() {
      // console.log(this.chooseClassify.activeName);
      this.getParamsData();
    },
    // 获取商品参数列表数据
    async getParamsData() {
      // 如果this.chooseClassify.selectedCateKeys这个数组的长度不是3证明，用户选择的不是三级分类，这个时候需要清空这个数组，并且退出函数
      if (this.chooseClassify.selectedCateKeys.length !== 3) {
        this.chooseClassify.selectedCateKeys = [];
        return;
      }
      //   否则，用户选择的就是三级分类
      //   console.log(this.chooseClassify.selectedCateKeys);
      //   当用户选中了三级分类的时候，发请求获取分类参数的数据
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.chooseClassify.activeName,
          },
        }
      );

      if (res.meta.status !== 200) {
        return this.$Elementui.Message.error(res.meta.msg);
      }

      // console.log(res.data);
      // 处理数据,将字符串attr_vals转换成数组
      res.data.forEach((item) => {
        // 给数组赋值之前做一下判断，如果是一个空字符串就把它返回一个空数组在赋值，如果不是，就进行分割
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : [];
        // 在这里将数组里面的每一项添加inputVisible和inputValue属性，以保证么每一个文本标签的私有性
        item.inputVisible = false;
        item.inputValue = '';
      });
      // 如果请求回来是动态参数就存储到动态参数数组里面
      if (this.chooseClassify.activeName === 'many') {
        this.chooseClassify.manyTableData = res.data;
      }
      // 如果请求回来是静态参数就存储到静态参数数组里面
      this.chooseClassify.onlyTableData = res.data;
    },
    // 显示添加动态参数的对话框
    showAddManyDataDialog() {
      this.chooseClassify.addManyDataVisible = true;
    },
    // 监听添加动态参数对话框的关闭事件
    addManyDataFormClosed() {
      this.$refs.addManyDataRef.resetFields();
    },
    // 显示添加静态属性的对话框
    showAddOnlyDataDialog() {
      this.chooseClassify.addOnlyDataVisible = true;
    },
    // 监听添加动态参数对话框的关闭事件
    addOnlyDataFormClosed() {
      this.$refs.addOnlyDataRef.resetFields();
    },

    // 添加动态参数
    addManyParams() {
      this.$refs.addManyDataRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.chooseClassify.addManyDataForm.attr_name,
            attr_sel: this.chooseClassify.activeName,
          }
        );
        if (res.meta.status !== 201) {
          return this.$Elementui.Message.error('添加动态参数失败！');
        }
        this.getParamsData();
        this.$Elementui.Message.success('添加动态参数成功！');
        this.chooseClassify.addManyDataVisible = false;
      });
    },

    // 添加静态参数
    addOnlyParams() {
      this.$refs.addOnlyDataRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.chooseClassify.addOnlyDataForm.attr_name,
            attr_sel: this.chooseClassify.activeName,
          }
        );
        if (res.meta.status !== 201) {
          return this.$Elementui.Message.error('添加静态属性失败！');
        }
        this.getParamsData();
        this.$Elementui.Message.success('添加静态属性成功！');
        this.chooseClassify.addOnlyDataVisible = false;
      });
    },
    // 显示修改动态参数对话框
    async showManyEditDialog(attrId) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        {
          params: {
            attr_sel: this.chooseClassify.activeName,
          },
        }
      );
      if (res.meta.status !== 200) {
        return this.$Elementui.Message.error(res.meta.msg);
      }
      this.chooseClassify.editManyDataForm = res.data;
      this.chooseClassify.editManyDataVisible = true;
    },
    // 显示修改静态属性对话框
    async showOnlyEditDialog(attrId) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        {
          params: {
            attr_sel: this.chooseClassify.activeName,
          },
        }
      );
      if (res.meta.status !== 200) {
        return this.$Elementui.Message.error(res.meta.msg);
      }
      this.chooseClassify.editOnlyDataForm = res.data;
      this.chooseClassify.editOnlyDataVisible = true;
    },

    // 监听修改动态参数对话框的关闭事件
    editManyDataFormClosed() {
      this.$refs.editManyDataRef.resetFields();
    },
    // 编辑动态参数
    editManyParams() {
      this.$refs.editManyDataRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.chooseClassify.editManyDataForm.attr_id}`,
          {
            attr_name: this.chooseClassify.editManyDataForm.attr_name,
            attr_sel: this.chooseClassify.activeName,
          }
        );
        if (res.meta.status !== 200) {
          return this.$Elementui.Message.error(res.meta.msg);
        }
        this.getParamsData();
        this.$Elementui.Message.success('修改动态参数成功！');
        this.chooseClassify.editManyDataVisible = false;
      });
    },

    // 监听修改静态属性对话框的关闭事件
    editOnlyDataFormClosed() {
      this.$refs.editOnlyDataRef.resetFields();
    },
    // 编辑静态属性
    editOnlyParams() {
      this.$refs.editOnlyDataRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.chooseClassify.editOnlyDataForm.attr_id}`,
          {
            attr_name: this.chooseClassify.editOnlyDataForm.attr_name,
            attr_sel: this.chooseClassify.activeName,
          }
        );
        if (res.meta.status !== 200) {
          return this.$Elementui.Message.error(res.meta.msg);
        }
        this.getParamsData();
        this.$Elementui.Message.success('修改动态参数成功！');
        this.chooseClassify.editOnlyDataVisible = false;
      });
    },

    // 根据id 值删除参数
    async removeParams(attrId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => {
        return err;
      });
      if (confirmResult !== 'confirm') {
        return this.$Elementui.Message.info('您已经取消了删除！');
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      );

      if (res.meta.status !== 200) {
        return this.$Elementui.Message.error('删除失败！');
      }
      this.getParamsData();
      this.$Elementui.Message.success('该数据已经删除成功！');
    },
    // 控制文本输入框的函数
    async handleInputConfirm(row) {
      // 切换为按钮之前做一个判断，没有输入真实有效的内容，就将row.inputValue清空重置，注意，字符串也可以使用length属性
      if (row.inputValue.trim().length === 0) {
        row.inputValue = '';
        row.inputVisible = false;
        return;
      }
      // 否则就将用户输入的值保存至attr_vals中
      row.attr_vals.push(row.inputValue);
      // 清空输入框的值
      row.inputValue = '';
      // 切换至按钮
      row.inputVisible = false;
      // 此时，发请求通知后端服务器修改属性
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          // 将数组拼接成字符串
          attr_vals: row.attr_vals.join(),
        }
      );
      if (res.meta.status !== 200) {
        return this.$Elementui.Message.error(res.meta.msg);
      }
      this.$Elementui.Message.success('修改参数属性成功！');
    },
    // 显示输入框
    showInput(row) {
      row.inputVisible = true;
      // 让输入框自动获取焦点的方法
      // 注意：执行了这行代码之后row.inputVisible = true;输入框并没有被渲染出来，此时页面中还是一个按钮，因此，要想自动获取输入框的焦点，就需要在输入框被渲染出来之后，再来执行，所以放到了$nextTick回调函数里面执行
      this.$nextTick((_) => {
        // 通过引用拿到页面中的input元素
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除参数文本标签
    async deleteTag(index, row) {
      row.attr_vals.splice(index, 1);
      // 发请求通知后天删除
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${row.attr_id}`
      );
      if (res.meta.status !== 200) {
        return this.$Elementui.Message.error(res.meta.msg);
      }
      this.$Elementui.Message.success('删除参数成功！');
    },
  },
  //  利用计算属性来监听添加参数和添加属性按钮的切换
  computed: {
    //   如果this.chooseClassify.selectedCateKeys.length为3的话，就是添加参数和属性，此时计算属性方法返回一个false,否则返回一个true
    isBtnDisabled() {
      if (this.chooseClassify.selectedCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 定义一个计算属性来获取发起获取参数的id值，这个id就是当前选中项三级分类的id,分类的id
    cateId() {
      if (this.chooseClassify.selectedCateKeys.length === 3) {
        //   将当前选中的三级分类的id 返回
        return this.chooseClassify.selectedCateKeys[2];
      }
      return null;
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
  .classify {
    margin: 15px 0;
    .el-cascader {
      margin-left: 15px;
    }
  }
}
.tags {
  margin: 5px 10px;
}
.input-new-tag {
  width: 100px;
}
</style>
